import { NextFunction, Request, Response } from 'express'
import jwt from 'jsonwebtoken'
import { config } from '../config'
import { User } from '../models/User'
import logger from '../utils/logger'
import { AppError } from './errorHandler'

interface JwtPayload {
  userId: string
}

export const authMiddleware = async (req: Request, res: Response, next: NextFunction) => {
  try {
    // 获取token
    const token = req.headers.authorization?.split(' ')[1]
    if (!token) {
      throw new AppError('No token provided', 401)
    }

    // 验证token
    const decoded = jwt.verify(token, config.jwt.secret) as JwtPayload

    // 检查用户是否存在
    const user = await User.findById(decoded.userId)
    if (!user) {
      throw new AppError('User not found', 404)
    }

    // 将用户信息添加到请求对象
    req.user = {
      id: user._id,
      username: user.username,
      role: user.role,
    }

    next()
  } catch (error) {
    logger.error('Auth middleware error:', error)
    if (error.name === 'JsonWebTokenError') {
      next(new AppError('Invalid token', 401))
    } else if (error.name === 'TokenExpiredError') {
      next(new AppError('Token expired', 401))
    } else {
      next(error)
    }
  }
}
